<?php

namespace App\Http\Controllers\SystemManagement;

use App\Http\Controllers\BaseController;
use App\Service\SystemManagement\TigerConfigService;
use Illuminate\Http\Request;

class TigerConfigController extends BaseController
{
    public function index(Request $request)
    {
        $module   = (string)$request->get('module', '');
        $name     = (string)$request->get('name', '');
        $pageNum  = (int)$request->get('pageNum', 1);
        $pageSize = (int)$request->get('pageSize', 20);
        return $this->success(TigerConfigService::index($module, $name, $pageNum, $pageSize));
    }

    public function save(Request $request)
    {
        $this->validate($request, [
            'module'      => 'required|string|max:120',
            'name'        => 'required|string|max:120',
            'type'        => 'required|string|in:json,string,int',
            'public'      => 'required|int|in:0,1',
            'value'       => 'required|string|max:65535',
            'description' => 'sometimes|string|max:255',
        ]);
        $userInfo = json_decode(json_encode($request->userInfo), true);
        try {
            $all = $request->only(['module', 'name', 'type', 'value', 'description', 'public']);
            TigerConfigService::save((int)$request->id, $all, $userInfo);
        } catch (\Exception $exception) {
            return $this->fail(400, $exception->getMessage());
        }
        return $this->success();
    }

    public function allModules()
    {
        return $this->success(collect(TigerConfigService::allModules())->map(function ($moduleName) {
            // 前端要这么写
            return [
                'id'   => $moduleName,
                'name' => $moduleName,
            ];
        })->toArray());
    }
}
